package com.eric.husky.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName: SpringUtils
 * @Description: spring 获取bean工具类
 */
@Component
public class SpringUtil implements ApplicationContextAware{
	/**
	 * 当前spring上下文
	 */
	private static ApplicationContext ctx;
	
	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		ctx = arg0;
	}
	/**
	 * 根据bean名称获取bean对象
	 * @param beanName
	 * @return
	 */
	public static <T>T getBean(String beanName){
		if(beanName == null || beanName.equals("")) return null;
		return getBean0(beanName);
	}
	/**
	 * 根据bean类型获取bean对象
	 * @param clz
	 * @return
	 */
	public static <T>T getBean(Class<T> clz){
		if(clz == null) return null;
		return getBean0(clz);
	}
	/**
	 * 根据bean类型获取所有的实现对象
	 * @param clz
	 * @return
	 */
	public static<T> Map<String,T> getBeans(Class<T> clz){
		if(clz == null) return null;
		return ctx.getBeansOfType(clz);
	}
	/**
	 * 私有方法，获取bean对象
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static <T>T getBean0(Object obj){
		if(ctx == null) return null;
		T bean = null;
		if(obj instanceof String){
			bean = (T) ctx.getBean((String)obj);
		}else{
			bean = ctx.getBean((Class<T>)obj);
		}
		return bean;
	}
}
